package com.aid.winter.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.aid.winter.common.constant.RoleConstants;
import com.aid.winter.common.exception.BusinessException;
import com.aid.winter.dto.request.*;
import com.aid.winter.dto.response.LoginVO;
import com.aid.winter.dto.response.PageResult;
import com.aid.winter.dto.response.UserVO;
import com.aid.winter.entity.SysUser;
import com.aid.winter.entity.UserWhitelist;
import com.aid.winter.mapper.SysUserMapper;
import com.aid.winter.mapper.UserWhitelistMapper;
import com.aid.winter.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements SysUserService {

    private final SysUserMapper userMapper;
    private final UserWhitelistMapper whitelistMapper;
    
    // 默认密码
    private static final String DEFAULT_PASSWORD = "123456";

    @Override
    public LoginVO login(LoginRequest request) {
        SysUser user;
        
        // 学生使用学号+身份证后六位登录
        if (StringUtils.hasText(request.getIdCard())) {
            user = userMapper.selectByStudentIdAndIdCard(request.getUsername(), request.getIdCard());
            if (user == null) {
                throw new BusinessException("学号或身份证号错误");
            }
        } 
        // 其他用户使用用户名密码登录
        else {
            if (!StringUtils.hasText(request.getPassword())) {
                throw new BusinessException("密码不能为空");
            }
            user = userMapper.selectByUsername(request.getUsername());
            if (user == null || !request.getPassword().equals(user.getPassword())) {
                throw new BusinessException("用户名或密码错误");
            }
        }
        
        // 判断用户状态
        if (user.getStatus() != 1) {
            throw new BusinessException("账号已被禁用");
        }
        
        // 添加白名单检查逻辑
        if (user.getRoleType() == RoleConstants.ROLE_SCHOOL) {
            UserWhitelist whitelist = whitelistMapper.selectByUserId(user.getId());
            if (whitelist == null) {
                throw new BusinessException("您暂未获得系统访问权限，请联系管理员");
            }
        }
        
        // 登录
        StpUtil.login(user.getId());
        // 设置角色
        StpUtil.getSession().set("roleType", user.getRoleType());
        
        // 返回登录信息
        LoginVO loginVO = new LoginVO();
        BeanUtils.copyProperties(user, loginVO);
        loginVO.setToken(StpUtil.getTokenValue());
        return loginVO;
    }

    @Override
    public SysUser getCurrentUser() {
        if (!StpUtil.isLogin()) {
            throw new BusinessException("用户未登录");
        }
        return getUserById(StpUtil.getLoginIdAsLong());
    }

    @Override
    public SysUser getUserById(Long id) {
        SysUser user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return user;
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserVO createUser(UserCreateRequest request) {
        // 验证用户名是否已存在
        SysUser existUser = userMapper.selectByUsername(request.getUsername());
        if (existUser != null) {
            throw new BusinessException("用户名已存在");
        }
        
        // 如果是学生角色，验证学号和身份证
        if (RoleConstants.ROLE_STUDENT == request.getRoleType()) {
            if (!StringUtils.hasText(request.getStudentId()) || !StringUtils.hasText(request.getIdCard())) {
                throw new BusinessException("学生用户必须填写学号和身份证");
            }
            // 验证学号是否已存在
            existUser = userMapper.selectByStudentIdAndIdCard(request.getStudentId(), request.getIdCard());
            if (existUser != null) {
                throw new BusinessException("学号已存在");
            }
        }
        
        SysUser user = new SysUser();
        BeanUtils.copyProperties(request, user);
        
        // 如果没有提供密码，则使用默认密码
        user.setPassword(StringUtils.hasText(request.getPassword()) ? request.getPassword() : DEFAULT_PASSWORD);
        user.setStatus(1); // 设置状态为启用
        
        userMapper.insert(user);
        
        return convertToVO(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserVO updateUser(Long id, UserUpdateRequest request) {
        SysUser user = getUserById(id);
        
        // 更新基本信息
        user.setRealName(request.getRealName());
        user.setPhone(request.getPhone());
        
        // 如果提供了身份证号，则更新
        if (StringUtils.hasText(request.getIdCard())) {
            user.setIdCard(request.getIdCard());
        }
        
        userMapper.updateById(user);
        
        return convertToVO(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(Long id, PasswordUpdateRequest request) {
        SysUser user = getUserById(id);
        
        // 验证原密码
        if (!user.getPassword().equals(request.getOldPassword())) {
            throw new BusinessException("原密码错误");
        }
        
        // 验证新密码不能与原密码相同
        if (request.getOldPassword().equals(request.getNewPassword())) {
            throw new BusinessException("新密码不能与原密码相同");
        }
        
        userMapper.updatePassword(id, request.getNewPassword());
        
        // 密码修改后，清除用户登录状态
        StpUtil.logout(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long id) {
        SysUser user = getUserById(id);
        userMapper.updatePassword(id, DEFAULT_PASSWORD);
        
        // 重置密码后，清除用户登录状态
        StpUtil.logout(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Long id, Integer status) {
        if (status != 0 && status != 1) {
            throw new BusinessException("无效的状态值");
        }
        
        SysUser user = getUserById(id);
        
        // 不允许禁用超级管理员
        if (RoleConstants.ROLE_ADMIN == user.getRoleType() && status == 0) {
            throw new BusinessException("不能禁用超级管理员账号");
        }
        
        userMapper.updateStatus(id, status);
        
        // 如果是禁用用户，则清除其登录状态
        if (status == 0) {
            StpUtil.logout(id);
        }
    }

    @Override
    public PageResult<UserVO> listUsers(Integer roleType, String username, String realName, 
                                      Integer pageNum, Integer pageSize) {
        int offset = (pageNum - 1) * pageSize;
        
        List<SysUser> users = userMapper.selectList(roleType, username, realName, offset, pageSize);
        long total = userMapper.selectCount(roleType, username, realName);
        
        List<UserVO> voList = users.stream()
                .map(this::convertToVO)
                .toList();
        
        return PageResult.build(voList, total, pageSize, pageNum);
    }

    private UserVO convertToVO(SysUser user) {
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        return vo;
    }
} 